//
//  ModifyUserInfoViewController.m
//  Rail
//
//  Created by hychen on 2018/3/10.
//  Copyright © 2018年 Hychen. All rights reserved.
//

#import "ModifyUserInfoViewController.h"
#import "BMDatePickerViewStyle.h"
#import "BMUsefulPickerView.h"
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <CoreLocation/CoreLocation.h>

@interface ModifyUserInfoViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic, strong) UserInfoModel *userInfoModel;
@property (nonatomic, strong) NSArray *educationArray;
@end

@implementation ModifyUserInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem addSimpleTitleView:@"个人信息"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)czh_setGroup
{
    [super czh_setGroup];

    [self.sectionGroups removeAllObjects];
    
    BMWeakSelf
    //
    CZHAvatartem *avatartem = [CZHAvatartem itemWithImageName:nil title:@"修改头像" canClick:YES];
    avatartem.avater = self.userInfoModel.logo_url;
    avatartem.operationBlock = ^(CZHBaseSettingItem *item, NSIndexPath *indexPath) {
        [weakSelf addAlertSheet];
    };
    CZHSettingFrameModel *avatarFrameModel = [[CZHSettingFrameModel alloc] init];
    avatarFrameModel.item = avatartem;
    
    //昵称
    CZHEditArrowItem *nickItem = [CZHEditArrowItem itemWithImageName:nil title:@"昵称" canClick:YES];
    nickItem.hideArrow = YES;
    nickItem.detail = self.userInfoModel.nickname?:@"";
    nickItem.placeholder = @"请输入您的昵称";
    nickItem.editCompleteBlock = ^(NSString *inputString) {//编辑完成回调
        BMStrongSelf
        if (![inputString isEqualToString:strongSelf.userInfoModel.nickname]) {
            strongSelf.userInfoModel.nickname = inputString;
            //请求接口
            [strongSelf requestData];
        }
    };
    CZHSettingFrameModel *nickFrameModel = [[CZHSettingFrameModel alloc] init];
    nickFrameModel.cellHeight = 50;
    nickFrameModel.bgColor = [UIColor whiteColor];
    nickFrameModel.item = nickItem;
    
    
    //姓名
    CZHArrowItem *nameItem = [CZHArrowItem itemWithImageName:nil title:@"姓名" canClick:NO];
    nameItem.hideArrow = YES;
    nameItem.detail = self.userInfoModel.username?:@"";
    CZHSettingFrameModel *nameFrameModel = [[CZHSettingFrameModel alloc] init];
    nameFrameModel.cellHeight = 50;
    nameFrameModel.bgColor = [UIColor whiteColor];
    nameFrameModel.detailColor = RGB(86, 86, 86);
    nameFrameModel.item = nameItem;
    
    //性别
    CZHArrowItem *sexItem = [CZHArrowItem itemWithImageName:nil title:@"性别" canClick:YES];
    sexItem.hideArrow = YES;
    sexItem.detail = self.userInfoModel.isMan?@"男":@"女";
    sexItem.operationBlock = ^(CZHBaseSettingItem *item, NSIndexPath *indexPath) {
        [BMUsefulPickerView showSingleColPickerWithToolBarText:@"请选择性别" data:@[@"女",@"男"] defaultIndex:self.userInfoModel.isMan toolBarStyle:BMPickerViewToolBarStyleText cancelBlock:^{
            
        } clickBlock:^(NSInteger selectedIndex, NSString *selectedValue) {
            //
            weakSelf.userInfoModel.sex = selectedIndex == 1?@"1":@"0";
            [weakSelf requestData];
        }];
    };
    CZHSettingFrameModel *sexFrameModel = [[CZHSettingFrameModel alloc] init];
    sexFrameModel.cellHeight = 50;
    sexFrameModel.bgColor = [UIColor whiteColor];
    sexFrameModel.item = sexItem;
    
    //手机号码
    CZHArrowItem *phoneItem = [CZHArrowItem itemWithImageName:nil title:@"手机号码" canClick:NO];
    phoneItem.hideArrow = YES;
    phoneItem.detail = self.userInfoModel.mobile?:@"";
    CZHSettingFrameModel *phoneFrameModel = [[CZHSettingFrameModel alloc] init];
    phoneFrameModel.cellHeight = 50;
    phoneFrameModel.bgColor = [UIColor whiteColor];
    phoneFrameModel.detailColor = RGB(167, 167, 167);
    phoneFrameModel.item = phoneItem;
    
    //身份证号
    CZHArrowItem *cardItem = [CZHArrowItem itemWithImageName:nil title:@"身份证号" canClick:NO];
    cardItem.hideArrow = YES;
    cardItem.detail = self.userInfoModel.cardno?:@"";
    CZHSettingFrameModel *cardFrameModel = [[CZHSettingFrameModel alloc] init];
    cardFrameModel.cellHeight = 50;
    cardFrameModel.bgColor = [UIColor whiteColor];
    cardFrameModel.detailColor = RGB(167, 167, 167);
    cardFrameModel.item = cardItem;
    
    //出生日期
    CZHArrowItem *birthItem = [CZHArrowItem itemWithImageName:nil title:@"出生日期" canClick:YES];
    birthItem.hideArrow = YES;
    birthItem.detail = self.userInfoModel.birthday?:@"点击选择出生日期";
    birthItem.operationBlock = ^(CZHBaseSettingItem *item, NSIndexPath *indexPath) {
        BMDatePickerViewStyle *style = [BMDatePickerViewStyle new];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSDate *now = [NSDate date];
        style.maximumDate = now;
        [BMUsefulPickerView showDatePickerWithToolBarText:@"请选择出生日期" withStyle:style toolBarStyle:BMPickerViewToolBarStyleText cancelBlock:^{
            
        } clickBlock:^(NSDate *selectedDate) {
            //保存出生日期
            NSString *birthday = [selectedDate formatYearMonthDay_lib];
            if (![birthday isEqualToString:weakSelf.userInfoModel.birthday]) {
                weakSelf.userInfoModel.birthday = birthday;
                [weakSelf requestData];
            }
        } valueChangeBlock:^(NSDate *selectedDate) {
            
        }];
    };
    CZHSettingFrameModel *birthFrameModel = [[CZHSettingFrameModel alloc] init];
    birthFrameModel.cellHeight = 50;
    birthFrameModel.bgColor = [UIColor whiteColor];
    birthFrameModel.item = birthItem;
    
    //电子邮箱
    CZHEditArrowItem *mailItem = [CZHEditArrowItem itemWithImageName:nil title:@"电子邮箱" canClick:YES];
    mailItem.hideArrow = YES;
    mailItem.detail = self.userInfoModel.email?:@"";
    mailItem.placeholder = @"请输入电子邮箱";
    mailItem.editCompleteBlock = ^(NSString *inputString) {//编辑完成回调
        BMStrongSelf
        if (![CheckUtility checkForEmail:inputString?:@""]) {
            Show_Msg_Error(@"电子邮箱格式错误")
            [weakSelf czh_setGroup];
            [weakSelf.tableView reloadData];
            return;
        }
        if (![inputString isEqualToString:strongSelf.userInfoModel.email]) {
            strongSelf.userInfoModel.email = inputString;
            //请求接口
            [strongSelf requestData];
        }
    };
    CZHSettingFrameModel *mailFrameModel = [[CZHSettingFrameModel alloc] init];
    mailFrameModel.cellHeight = 50;
    mailFrameModel.bgColor = [UIColor whiteColor];
    mailFrameModel.item = mailItem;
    
    //专业
    CZHArrowItem *majorItem = [CZHArrowItem itemWithImageName:nil title:@"专业" canClick:NO];
    majorItem.hideArrow = YES;
    majorItem.detail = self.userInfoModel.specialty?:@"";
    CZHSettingFrameModel *majorFrameModel = [[CZHSettingFrameModel alloc] init];
    majorFrameModel.cellHeight = 50;
    majorFrameModel.bgColor = [UIColor whiteColor];
    majorFrameModel.item = majorItem;
    
    //学历
    CZHArrowItem *educationItem = [CZHArrowItem itemWithImageName:nil title:@"学历" canClick:YES];
    educationItem.hideArrow = YES;
    educationItem.detail = self.userInfoModel.education?:@"";
    NSInteger index = [self.educationArray indexOfObject:self.userInfoModel.education];
    educationItem.operationBlock = ^(CZHBaseSettingItem *item, NSIndexPath *indexPath) {
        //选择学历 小学，初中，高中，专科，本科，研究生，博士
        [BMUsefulPickerView showSingleColPickerWithToolBarText:@"请选择学历" data:weakSelf.educationArray defaultIndex:index toolBarStyle:BMPickerViewToolBarStyleText cancelBlock:^{
            
        } clickBlock:^(NSInteger selectedIndex, NSString *selectedValue) {
            //
            weakSelf.userInfoModel.education = selectedValue;
            [weakSelf requestData];
        }];
    };
    CZHSettingFrameModel *educationFrameModel = [[CZHSettingFrameModel alloc] init];
    educationFrameModel.cellHeight = 50;
    educationFrameModel.bgColor = [UIColor whiteColor];
    educationFrameModel.item = educationItem;
    
    //岗位
    CZHEditArrowItem *jobItem = [CZHEditArrowItem itemWithImageName:nil title:@"岗位" canClick:YES];
    jobItem.hideArrow = YES;
    jobItem.detail = self.userInfoModel.job?:@"";
    jobItem.placeholder = @"请输入您的岗位";
    jobItem.editCompleteBlock = ^(NSString *inputString) {//编辑完成回调
        BMStrongSelf
        if (![inputString isEqualToString:strongSelf.userInfoModel.job]) {
            strongSelf.userInfoModel.job = inputString;
            //请求接口
            [strongSelf requestData];
        }
    };
    CZHSettingFrameModel *jobFrameModel = [[CZHSettingFrameModel alloc] init];
    jobFrameModel.cellHeight = 50;
    jobFrameModel.bgColor = [UIColor whiteColor];
    jobFrameModel.item = jobItem;
    
    
    CZHSectionItem *sectionZero = [[CZHSectionItem alloc] init];
    sectionZero.items = @[avatarFrameModel];
    [self.sectionGroups addObject:sectionZero];
    
    CZHSectionItem *sectionOne = [[CZHSectionItem alloc] init];
    sectionOne.headHeight = 10;
    sectionOne.items = @[nickFrameModel,nameFrameModel,sexFrameModel,phoneFrameModel,cardFrameModel,birthFrameModel,mailFrameModel,majorFrameModel,educationFrameModel,jobFrameModel];
    [self.sectionGroups addObject:sectionOne];
}

- (UserInfoModel *)userInfoModel {
    return [GlobalManage sharedManage].userInfoModel;
}

- (void)requestData {
    NSString *nickname = self.userInfoModel.nickname?:@"";
    NSString *sex = self.userInfoModel.sex?:@"1";
    NSString *email = self.userInfoModel.email?:@"";
    NSString *birthday = self.userInfoModel.birthday?:@"";
    NSString *job = self.userInfoModel.job?:@"";
    NSString *education = self.userInfoModel.education?:@"";
    BMWeakSelf
    [[NetworkTool sharedNetworkTool] requestDataWithParams:@[API_App_User_Update,nickname,sex,email,birthday,job,education] authType:AUTH_LOGIN dataType:JSON_ITEM Success:^(id obj) {
        [weakSelf czh_setGroup];
        [weakSelf.tableView reloadData];
    } Failure:^(NSString *code, NSString *msg) {
        Show_SV_Error_Msg(msg)
        weakSelf.userInfoModel = [GlobalManage sharedManage].userInfoModel;
        [weakSelf czh_setGroup];
        [weakSelf.tableView reloadData];
    }];
}

- (void)updateAvatar:(UIImage *)image {
    Show_Msg(@"上传头像中")
    BMWeakSelf
    [HttpRequest uploadAvatarWithImage:image success:^(id object) {
        NSString *avatar_url = @"";
        if ([object isKindOfClass:[NSString class]]) {
            avatar_url = (NSString *)object;
        }
        else if ([object isKindOfClass:[NSDictionary class]]) {
            avatar_url = [object objectForKey:@"logo_url"];
        }
        
        if ([avatar_url isKindOfClass:[NSString class]] && avatar_url.length > 0) {
            [GlobalManage sharedManage].headImageUrl = avatar_url;
            [GlobalManage sharedManage].userInfoModel.logo_url = avatar_url;
            [weakSelf.tableView reloadData];
            [[NSNotificationCenter defaultCenter] postNotificationName:Notify_Upload_Avatar_Success object:nil];
            Show_Msg_Success(@"上传头像成功")
            [weakSelf czh_setGroup];
            [weakSelf.tableView reloadData];
        }
        else {
            Show_Msg_Error(@"上传头像失败")
        }
    } failure:^(NSString *code, NSString *msg) {
        Show_Msg_Error(@"上传头像失败")
    }];
}

#pragma mark - 相册
- (void)addAlertSheet {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self alertClickedButtonAtIndex:0];
    }];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self alertClickedButtonAtIndex:1];
    }];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alert addAction:action];
    [alert addAction:action1];
    [alert addAction:action3];
    
    
    [self.navigationController presentViewController:alert animated:YES completion:nil];
}

- (void)alertClickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:
            //来源:相机
            if ([self requestCameraAuth]) {
                [self goToCameraVc];
            }
            return;
        case 1:
            //来源:相册
            [self checkPhotoAuth];
            return;
        case 2:
            return;
    }
}

- (void)goToCameraVc {
    // 跳转到相机或相册页面
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    
    [self.navigationController presentViewController:imagePickerController animated:YES completion:^{
        
    }];
}

- (void)goToPhotoVc {
    // 跳转到相机或相册页面
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    [self.navigationController presentViewController:imagePickerController animated:YES completion:^{
        
    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    image = [self imageWithImage:image scaledToSize:CGSizeMake(50, 50)];
    
    [self updateAvatar:image];
    
}


- (UIImage *)imageWithImage:(UIImage*)image
               scaledToSize:(CGSize)newSize {
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

- (NSArray *)educationArray {
    return @[@"小学",@"初中",@"高中",@"专科",@"本科",@"研究生",@"博士"];
}

- (BOOL)requestCameraAuth {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus ==AVAuthorizationStatusRestricted ||//此应用程序没有被授权访问的照片数据。可能是家长控制权限
        authStatus ==AVAuthorizationStatusDenied)  //用户已经明确否认了这一照片数据的应用程序访问
    {
        // 无权限 引导去开启
        [UIAlertView bk_showAlertViewWithTitle:@"提示" message:@"需要开启相机权限才能拍摄照片哦" cancelButtonTitle:@"取消" otherButtonTitles:@[@"去开启"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                if (IOS8) {
                    NSURL *settingURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                    if ([[UIApplication sharedApplication] canOpenURL:settingURL]) {
                        [[UIApplication sharedApplication] openURL:settingURL];
                    }
                }
            }
        }];
        return NO;
    }
    return YES;
}

// 检查授权
- (void)checkPhotoAuth
{
    BMWeakSelf
    [BMPhotoIOAuthTool checkAuthForPhotoWithAuthedStatus:^(PHAuthorizationStatus status) {
        [weakSelf goToPhotoVc];
    } denied:^(PHAuthorizationStatus status) {
        [weakSelf requestPhotoAuth];
    } noRequest:^(PHAuthorizationStatus status) {
        [weakSelf requestPhotoAuth];
    }];
}

// 请求授权
- (void)requestPhotoAuth
{
    BMWeakSelf
    [BMPhotoIOAuthTool requestAuthForPhotoWithAuthedStatus:^(PHAuthorizationStatus status) {
        [weakSelf goToPhotoVc];
    } denied:^(PHAuthorizationStatus status) {
        [UIAlertView bk_showAlertViewWithTitle:@"提示" message:@"需要开启相册权限才能查看照片哦" cancelButtonTitle:@"取消" otherButtonTitles:@[@"去开启"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                if (IOS8) {
                    NSURL *settingURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                    if ([[UIApplication sharedApplication] canOpenURL:settingURL]) {
                        [[UIApplication sharedApplication] openURL:settingURL];
                    }
                }
            }
        }];
    }];
}
@end
